#!/usr/bin/python26

#Copyright 2012 University of Western Sydney

#Licensed under the Apache License, Version 2.0 (the "License");
#you may not use this file except in compliance with the License.
#You may obtain a copy of the License at

#    http://www.apache.org/licenses/LICENSE-2.0

#Unless required by applicable law or agreed to in writing, software
#distributed under the License is distributed on an "AS IS" BASIS,
#WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#See the License for the specific language governing permissions and
#limitations under the License.



import web
import urllib,json
import string
	
urls = (
	'/(.*)', 'hello'
)
app = web.application(urls, globals())
center_lat = "-34"
center_lng = "152"
radius = 450
maxKMLReturns = 50

class hello:	

	def GET(self, name):
		user_data = web.input(BBOX="141,-22,154,-12") # reef

		BOXIN = user_data.BBOX

		print "BBOX=" + BOXIN
		bbox = BOXIN.split(',')
		west = float(bbox[0])
		south = float(bbox[1])
		east = float(bbox[2])
		north = float(bbox[3])

		radius = (east - west) * 80 / 2 # 111.1 km per degree
 
		center_lng = ((east - west) / 2) + west
		center_lat = ((north - south) / 2) + south
		lat_str = str(center_lat)
		lng_str = str(center_lng)

		print "center=" + lat_str + "," + lng_str

		# ip was 115.146.92.238
		pageUrl="http://localhost:8983/solr/select?wt=json&indent=true&fl=id&q=*:*&fq={!geofilt%20pt=" + lat_str + "," + lng_str + "%20sfield=store%20d=" + str(radius) + "}&facet=true&facet.field=container"

		print "pageUrl=" + pageUrl

		if not name: 
			name = 'World'	    

		try: response = urllib.urlopen( pageUrl )
		except URLError, e:
			print e.reason
		html = response.read()
		#print "html=" + html
		result = json.loads( html )

		containerUrl = "http://localhost:8983/solr/select?q=id:%s&wt=json&fl=kml"

		count = 0
		lastContainer = ""
		kmlCount = 0

		output = "<kml xmlns=\"http://earth.google.com/kml/2.1\"\nxmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\nxsi:schemaLocation=\"http://earth.google.com/kml/2.1  http://code.google.com/apis/kml/schema/kml21.xsd\">\n"
		output += "<Document>\n"

		for container in result["facet_counts"]["facet_fields"]["container"]:

			if kmlCount < maxKMLReturns:
				if count % 2 == 0: # row 0,2,4,6,8...
					lastContainer = container
					#print str(count) + ": " + lastContainer
				else:
					# print "odd " + str(container) + " kmlCount:" + str(kmlCount)
					if int(container) > 0:
						cUrl = containerUrl % lastContainer
						# print "getting " + cUrl
						cf = urllib.urlopen( cUrl ) # go get container
						kmlPlus = json.loads( cf.read() )["response"]["docs"][0]["kml"].encode('utf-8')
						import re
						kmlPlus = re.sub("<\?xml.*?>","",kmlPlus)
						#kmlPlus = re.sub("</?kml.*?>","",kmlPlus, re.MULTILINE,re.DOTALL)
						#kmlPlus = re.sub("</?kml.*?>","",kmlPlus, re.DOTALL)
						kmlPlus = re.sub("<kml.*","",kmlPlus) # strip kml headers
						kmlPlus = re.sub("xmlns:.*","",kmlPlus)
						kmlPlus = re.sub("xsi:.*","",kmlPlus)
						kmlPlus = re.sub("</kml>","",kmlPlus)
						kmlPlus = re.sub("<TimeSpan>","",kmlPlus) # strip timespans
						kmlPlus = re.sub("<begin>.*","",kmlPlus)
						kmlPlus = re.sub("<end>.*","",kmlPlus)
						kmlPlus = re.sub("</TimeSpan>","",kmlPlus)
						kmlPlus = re.sub("</description>","]]></description>",kmlPlus) # add missing CDATA close
						kmlPlus = re.sub("Document>","Folder>",kmlPlus)
		
						output += str(kmlPlus)
						kmlCount += 1
					
			count += 1

		output += "</Document>\n"
		output += "</kml>"
		
		return output

if __name__ == "__main__":
    app.run()
